package com.example.security.config.manager;

import com.example.security.config.XmxSecurityConfig;
import com.example.security.model.Menu;
import com.example.security.model.Role;
import com.example.security.service.MenuService;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.util.AntPathMatcher;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class CustomFilterInvocationSecurityMetadataSource implements FilterInvocationSecurityMetadataSource {
    private MenuService menuService;
    public CustomFilterInvocationSecurityMetadataSource(MenuService menuService){
        this.menuService = menuService;
    }
    /**
     *  根据浏览器访问的url与数据库中加载的权限url匹配，获取访问的需要的角色
     * @param object     该方法的参数是一个Filterinvocation
     * @return
     * @throws IllegalArgumentException
     */
    @Override
    public Collection<ConfigAttribute> getAttributes(Object object) throws IllegalArgumentException {
        //1.获取当前的请求url   如：/user/hello
        String requestUrl = ((FilterInvocation) object).getRequestUrl();
        System.out.println("requestUrl========>"+requestUrl);
        //2.从数据库加载权限url 如：/admin/**   /dba/**   /user/**
        List<Menu> menuList = menuService.queryMenuAndRelationRoles();
        //3.从匹配的权限url中查询需要的角色
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (Menu menu : menuList) {
            if(antPathMatcher.match( menu.getPattern(),requestUrl)){
                List<Role> roleList = menu.getRoleList();
                String[] roleArr = new String[roleList.size()];
                for(int i = 0; i < roleArr.length; i++){
                    roleArr[i] = roleList.get(i).getName();
                }
                return SecurityConfig.createList(roleArr);
            }
        }

        //4.获取用户具有角色与浏览器访问url的角色是否匹配，匹配就运行访问，否者报403 =====>spring security帮我们完成了
        //如 果当前请求的URL在资源表中不存在相应的模式，就假设该请求登录后即可访问，即直接返 回 ROLE_LOGIN。
        return  SecurityConfig.createList("ROLE_LOGIN");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }
    @Override
    public boolean supports(Class<?> clazz){
        return FilterInvocation.class.isAssignableFrom(clazz);
    }
}
